package com.cloudcc.mobile.service;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.entity.login.LoginUser;
import com.cloudcc.mobile.parser.LoginParser;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.util.Tools;
/**
 * 后台登陆serivce获取最新building
 * @author Administrator
 *
 */
public class BindingService extends Service {
	private Timer myTimer;
	private int isfirst=0;
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	@Override
	public void onCreate() {
		try {
			myTimer=new Timer();
			TimerTask loginTask=new TimerTask() {
				@Override
				public void run() {
					if(NetWork.detect(BindingService.this)){
						if(isfirst==0){
							isfirst=1;
						}else{
							myHandler.sendEmptyMessage(1);
						}
					}
				}
			};
			myTimer.schedule(loginTask, 0, 1800000);
		} catch (Exception e) {
			Tools.handle(e);
		}
		super.onCreate();
	}
	
	Handler myHandler=new Handler(){@Override
	public void handleMessage(Message msg) {
		try {
			switch (msg.what) {
			case 1:
//				if(isfirst!=0){
//					Intent intent=new Intent(MyApplication.GET_WEIXIN_LOGIN);
//					sendBroadcast(intent);
//				}
//				isfirst++;
				new MyTask().execute();
				break;
			}
		} catch (Exception e) {
			Tools.handle(e);
		}
		super.handleMessage(msg);
	}};
	class MyTask extends AsyncTask<Void, Void, String>{
		@Override
		protected String doInBackground(Void... params) {
			String result="";
			try {
				LoginService service=new LoginService();
				//result =service.login(UserManager.getManager().getUser().); //TODO 自动登录
			} catch (Exception e) {
				Tools.handle(e);
			}
			return result;
		}
		@Override
		protected void onPostExecute(String result) {
			try {
				if(Tools.isNull(result)||result.equals("outTime")){
					return;
				}
				@SuppressWarnings("unused")
				LoginUser userinfo=new LoginUser();
				userinfo=LoginParser.getLoginUser(result,BindingService.this);
				super.onPostExecute(result);
			} catch (Exception e) {
				Tools.handle(e);
			}
		}
		
	}
	@Override
	public void onDestroy() {
		try {
			if(AppContext.isStopService){
				myTimer.cancel();
				Intent intent=new Intent(this,BindingService.class);
				stopService(intent);
			}else{
				Intent intent=new Intent(this,BindingService.class);
				startService(intent);
			}
			super.onDestroy();
		} catch (Exception e) {
			Tools.handle(e);
		}
	}
}
